<?php
namespace Src\Middleware;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Psr7\Factory\ResponseFactory;
use Src\utils\ResponseUtils;
class AdminMiddleware
{
    private $responseFactory;
    public function __construct(ResponseFactory $responseFactory)
    {
        $this->responseFactory = $responseFactory;
    }

    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler)
    {
        $user = $request->getAttribute('user');
        if (!$user || $user->role !== 'admin') {
            $response = $this->responseFactory->createResponse();
            $data = [
                'code' => 402,
                'success' => false,
                'message' => 'Admin access required'
            ];
            $response = ResponseUtils::withJson($response, $data, 403);
            return $response;
        }
        return $handler->handle($request);
    }
}